<template>
  <div>
    <!-- <div style="text-align: center;margin: 20px 0;font-size: 24px;color: #666; ">
      <b>样衣报表（按照部门维度）</b>
    </div> -->
    <!-- <div style="margin: 20px 0;">
      <SearchFormDate :curData="curData" ref="resetCommon" @child="child"></SearchFormDate>
    </div>
    <p style="margin: 20px 0;"> -->
    <!-- <el-button @click="$refs.plTreeTable.toggleTreeExpansion(treeData[1])">切换第二个</el-button>
          <el-button @click="$refs.plTreeTable.setTreeExpansion(treeData[1], true)">展开第二个</el-button> -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-button size="mini" @click="$refs.plTreeTable.clearTreeExpand()"
            >关闭所有</el-button
          >

          <el-button
            size="mini"
            @click="$refs.plTreeTable.setAllTreeExpansion()"
            >展开全部</el-button
          ><!-- <el-button @click="getTreeExpansionEvent">获取已展开</el-button> -->
        </el-col>
        <timeSearch
          @getDateArr="getDateArr"
          @changDay="changDay"
          :timeArr="timeArr"
          :dayActive="this.dayActive"
          :dayLimit="1095"
        />
      </el-row>
    </el-card>
    <!-- </p> -->
    <!-- <div>

      <el-col class="header" :span="3"> 部门</el-col>
      <el-col class="header" :span="3">发货量</el-col>
      <el-col class="header" :span="3">退货量</el-col>
      <el-col class="header" :span="3">退货比例</el-col>
      <el-col class="header" :span="3">归还</el-col>
      <el-col class="header" :span="3">未归还</el-col>
      <el-col class="header" :span="3">归还比例</el-col>
    </div> -->
    <div ref="tableDom">
      <u-table
        :maxHeight="tableHeight"
        :data="wmsItemTypeList"
        ref="plTreeTable"
        fixed-columns-roll
        header-drag-style
        :height="height"
        :treeConfig="{
          children: 'children',
          iconClose: 'el-icon-folder-add',
          iconOpen: 'el-icon-folder-remove',
          expandAll: false,
        }"
        @toggle-tree-expand="toggleTreeExpand"
        use-virtual
        row-id="userName"
        border
      >
        <!--u-table大数据表格 你需要在列上指定某个列显示展开收起 treeNode属性 :expand-row-keys="expandRowKeys" -->
        <!-- <u-table-column :tree-node="true" prop="label" label="我是树节点" fixed :width="215" />
          <u-table-column prop="id" label="id" fixed :width="215" /> -->
        <u-table-column
          :tree-node="true"
          prop="userName"
          label="部门"
          fixed
          :width="215"
        />
        <u-table-column
          prop="sampleNum"
          label="发货量"
          fixed
          :width="215"
          align="center"
        >
        </u-table-column>
        <u-table-column
          prop="returnedNum"
          label="退货量"
          fixed
          :width="215"
          align="center"
        >
        </u-table-column>
        <u-table-column
          prop="returnedRatioStr"
          label="退货比例"
          fixed
          :width="215"
          align="center"
        >
        </u-table-column>
        <u-table-column
          prop="returnNum"
          label="归还"
          fixed
          :width="215"
          align="center"
        >
        </u-table-column>
        <u-table-column
          prop="noReturnNum"
          label="未归还"
          fixed
          :width="215"
          align="center"
        >
        </u-table-column>
        <u-table-column
          prop="returnRatioStr"
          label="归还比例"
          fixed
          :width="215"
          align="center"
        >
        </u-table-column>
        <!-- <u-table-column v-for="item in columns" :key="item.id" :prop="item.prop" :label="item.label"
              :width="item.width" /> -->
      </u-table>
    </div>
  </div>
</template>

<script>
import timeSearch from "./day.vue";
import {
  listApplydwd,
  getApplydwd,
  delApplydwd,
  addApplydwd,
  updateApplydwd,
  selectdeptUserSampleNum,
  selectdeptSampleNum,
} from "@/api/sample/applydwd";

export default {
  components: {
    timeSearch,
  },
  data() {
    return {
      //试着去记录生活，心里想的跟李静丽那么多年没见过，只是在微信上这么聊着，
      //觉得生活平淡，需要点缀
      //我比较慢热，可能神经被锁住了，需要一把钥匙。
      //有时候觉得谈恋爱是渴望被爱，渴望被爱是个人权利，
      wmsItemTypeList: [],
      // 要展开的行，数值的元素是row的key值
      // expandRowKeys: [],
      tableHeight: "",
      sums: {},
      height: 750,
      dayActive: 1,
      timeArr: [
        { value: "1", label: "今天" },
        { value: "2", label: "昨天" },
        { value: "7", label: "最近7天" },
        { value: "30", label: "最近30天" },
      ],
      timeGap: { startTime: "", endTime: "" },
      // columns: Array.from({ length: 10 }, (_, idx) => ({
      //   prop: 'address', id: idx, label: '地址' + idx, width: 200
      // }))
    };
  },
  //记得清空  如果在keepalive中 则使用activated  deactivated
  destroyed() {
    window.onresize = null;
  },
  // computed: {
  //   treeData() {
  //     const newData = [...this.treeData]; // 创建一个新的数组，避免修改原始数据
  //     const totalRow = { column1: "合计", column2: 0, column3: 0 }; // 合计行的数据

  //     // 计算合计值
  //     // this.treeData.forEach(item => {
  //     //     totalRow.column2 += item.column2;
  //     //     totalRow.column3 += item.column3;
  //     // });
  //     // 将合计行插入到正确的位置
  //     newData.splice(4, 0, totalRow); // 假设将合计行插入到第二行的位置

  //     return newData;
  //   }
  // },
  mounted() {
    var _this = this;
    this.resizeTable();
    window.onresize = function () {
      _this.resizeTable();
    };
    //
    // console.log(500 + (500 * 500) + (500 * 500 * 10))
    // const data = Array.from({ length: 500 }, (_, idx) => ({
    //     id: idx + '_' + 1,
    //     date: '2016-05-03',
    //     name: 1,
    //     ab: '欢迎使用u-table',
    //     address: idx,
    //     children: Array.from({ length: 2 }, (_, idx2) => ({
    //         id: idx + '_' + idx2 + '_' + 1,
    //         date: '2016-05-03',
    //         name: 1,
    //         ab: '欢迎使用u-table',
    //         address: idx + '_' + idx2,
    //         children: Array.from({ length: 1 }, (_, idx3) => ({
    //             id: idx + '_' + idx2 + '_' + idx3 + '_' + 1,
    //             date: '2016-05-03',
    //             name: 1,
    //             ab: '欢迎使用u-table',
    //             address: idx + '_' + idx2 + '_' + idx3
    //         }))
    //     }))
    // }));

    // var data = []
    // deptTreeSelect().then(response => {
    //     // this.treeData = response.data;
    //     data = response.data;
    //     console.log(JSON.stringify(data));
    //     this.treeData = data // 知道为啥treeData不在 data()方法里面定义吗？嘻嘻
    //     // 设置表格数据
    //     this.$refs.plTreeTable.reloadData(data)
    //     // 获取表格实例，里面可以得到列，表格数据等等
    //     console.log(this.$refs.plTreeTable.tableExample())
    // });
    // console.log(JSON.stringify(data));

    // this.getList()

    // this.getselectdeptSampleNum()
  },
  methods: {
    changDay(val) {
      this.dayActive = val;
      this.timeGap.startTime = val[0];
      this.timeGap.endTime = val[1];
    },
    getDateArr(value) {
      this.timeGap.startTime = value[0];
      this.timeGap.endTime = value[1];
      console.log(JSON.stringify(this.timeGap));
      // const obj = { startDate: this.timeGap.startTime, endDate: this.timeGap.endTime, shopName: this.queryParams.shopName }
      const obj = {
        sampleDayStart: this.timeGap.startTime,
        sampleDayEnd: this.timeGap.endTime,
        dateYearStart: this.timeGap.startTime.slice(0, 4),
        dateYearEnd: this.timeGap.endTime.slice(0, 4),
        dateMonthStart: this.timeGap.startTime.slice(5, 7),
        dateMonthEnd: this.timeGap.endTime.slice(5, 7),
      };
      // this.getList(obj)
      this.getselectdeptSampleNum(obj);

      // this.dayActive = 1
    },
    child(objArgu, weekTime) {
      this.objArgu = objArgu;
      this.params.queryType = objArgu.cType;
      this.params.startDate = objArgu.beginTime;
      this.params.endDate = objArgu.endTime;
      this.weekTime = weekTime;
      console.log(JSON.stringify(this.params));
      if (this.params.queryType == 1) {
        // console.log(1);
        const obj = {
          sampleDayStart: this.params.startDate,
          sampleDayEnd: this.params.endDate,
        };
        this.getselectdeptSampleNum(obj);
        this.getList(obj);
      }
      if (this.params.queryType == 3) {
        // console.log(1);
        const obj = {
          dateYearStart: this.params.startDate.slice(0, 4),
          dateYearEnd: this.params.endDate.slice(0, 4),
          dateMonthStart: this.params.startDate.slice(5, 7),
          dateMonthEnd: this.params.endDate.slice(5, 7),
        };
        console.log(JSON.stringify(obj));
        // return
        this.getselectdeptSampleNum(obj);
        this.getList(obj);
      }
      if (this.params.queryType == 4) {
        // console.log(1);
        const obj = {
          dateYearStart: this.params.startDate.slice(0, 4),
          dateYearEnd: this.params.endDate.slice(0, 4),
        };
        console.log(JSON.stringify(obj));
        // return
        this.getselectdeptSampleNum(obj);
        this.getList(obj);
      }
    },
    getList(queryParams) {
      selectdeptUserSampleNum(queryParams).then((response) => {
        // this.applydwdList = response;
        const tree = this.convertToTree(response);
        console.log(JSON.stringify(tree));
        const data = [];
        for (let key in tree) {
          console.log(key); // 输出对象的键（"商品部"和"采购部"）
          console.log(JSON.stringify(tree[key])); // 输出对象的值（对应的子对象）
          data.push(tree[key]);
        }
        console.log(JSON.stringify(data));
        const totalRow = {
          userName: "汇总",
          sampleNum: this.sums.sampleNum,
          returnedNum: this.sums.returnedNum,
          returnedRatioStr: this.sums.returnedRatio,
          returnNum: this.sums.returnNum,
          noReturnNum: this.sums.noReturnNum,
          returnRatioStr: this.sums.returnRatio,
        }; // 合计行的数据
        data.splice(0, 0, totalRow); // 假设将合计行插入到第二行的位置
        this.$forceUpdate();

        this.treeData = data; // 知道为啥treeData不在 data()方法里面定义吗？嘻嘻
        // 设置表格数据
        this.wmsItemTypeList = data;

        // this.$nextTick(() => {
        // this.$refs.plTreeTable.reloadData(data)
        // });
      });
    },
    //汇总
    getselectdeptSampleNum(queryParams) {
      selectdeptSampleNum(queryParams).then((data) => {
        const result = data.reduce(
          (accumulator, currentValue) => {
            accumulator.sampleNum += currentValue.sampleNum;
            accumulator.returnNum += currentValue.returnNum;
            accumulator.noReturnNum += currentValue.noReturnNum;
            accumulator.returnedNum += currentValue.returnedNum;
            accumulator.returnedRatio =
              Number(
                (accumulator.returnedNum / accumulator.sampleNum) * 100
              ).toFixed(2) + "%";
            accumulator.returnRatio =
              (
                (accumulator.returnNum /
                  (Number(accumulator.returnNum) +
                    Number(accumulator.noReturnNum))) *
                100
              ).toFixed(2) + "%";

            return accumulator;
          },
          {
            sampleNum: 0,
            returnNum: 0,
            noReturnNum: 0,
            returnedNum: 0,
            returnedRatio: "",
            returnRatio: "",
          }
        );
        this.sums = result;
        this.$forceUpdate();

        console.log(JSON.stringify(result));
        const obj = {
          sampleDayStart: this.timeGap.startTime,
          sampleDayEnd: this.timeGap.endTime,
          dateYearStart: this.timeGap.startTime.slice(0, 4),
          dateYearEnd: this.timeGap.endTime.slice(0, 4),
          dateMonthStart: this.timeGap.startTime.slice(5, 7),
          dateMonthEnd: this.timeGap.endTime.slice(5, 7),
        };
        this.getList(obj);
      });
    },
    //树
    convertToTree(data) {
      const tree = {};
      data.forEach((item) => {
        const deptName = item.deptName;
        if (!tree[deptName]) {
          // tree[deptName] = {
          tree[deptName] = {
            children: [],
            // count: 0,
            sampleNum: 0,
            returnNum: 0,
            noReturnNum: 0,
            returnedNum: 0,
            sendRatio: 0,
            returnRatio: 0,
            returnedRatio: 0,
            returnRatioStr: "",
            returnedRatioStr: "",
            userName: item.deptName,
            id: 0,
          };
        }
        // tree[deptName].children.push(item);
        tree[deptName].children.push(item);
        tree[deptName].id++;
        tree[deptName].sampleNum += item.sampleNum;
        tree[deptName].returnNum += item.returnNum;
        tree[deptName].noReturnNum += item.noReturnNum;
        tree[deptName].returnedNum += item.returnedNum;
        tree[deptName].sendRatio += item.sendRatio;
        tree[deptName].returnRatio += item.returnRatio;
        tree[deptName].returnedRatio += item.returnedRatio;
      });

      // Calculate average values
      Object.values(tree).forEach((node) => {
        // node.sendRatio /= node.count;
        // node.returnRatio /= node.count;
        // node.returnedRatio /= node.count;
        node.returnRatioStr =
          (
            (node.returnNum /
              (Number(node.returnNum) + Number(node.noReturnNum))) *
            100
          ).toFixed(2) + "%";
        node.returnedRatioStr =
          ((node.returnedNum / node.sampleNum) * 100).toFixed(2) + "%";
      });

      return tree;
    },
    //合计行
    addTotal({ columns, data }) {
      // const { columns, data } = param;
      const sums = [];
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums[columnIndex] = "总计";
          return;
        }
        // if (columnIndex === 2) {
        //   sums[columnIndex] = 'N/A';
        //   return;
        // }
        // if (columnIndex  === 3) {
        //   sums[columnIndex ] = 'N/A';
        //   return;
        // }
        const values = data.map((item) => Number(item[column.property]));

        if (!values.every((value) => isNaN(value))) {
          sums[columnIndex] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[columnIndex] += "";
        } else {
          sums[columnIndex] = "N/A";
        }

        if (columnIndex === 3) {
          var point = sums[2] / sums[1];
          var str = Number(point * 100).toFixed(2);
          str += "%";
          sums[columnIndex] = str;
        }
        if (columnIndex === 6) {
          var sum = Number(sums[4]) + Number(sums[5]);
          console.log(sum);
          var point = sums[4] / sum;
          var str = Number(point * 100).toFixed(2);
          str += "%";
          sums[columnIndex] = str;
        }
      });
      this.sums = sums;

      console.log(JSON.stringify(sums));
      return sums;
    },
    // 获取已经展开的节点
    getTreeExpansionEvent() {
      console.log(this.$refs.plTreeTable.getTreeExpandRecords());
    },
    // 收起展开时触发
    toggleTreeExpand(row, treeExpanded, event) {
      console.log(row, treeExpanded, event);
      console.log(JSON.stringify(row));
      console.log(JSON.stringify(treeExpanded));
      console.log(JSON.stringify(event));
      // treeExpanded.forEach(item => {
      //   this.expandRowKeys.push(row);
      // });
    },
    // table自动高度
    returnTableHeight(ref, bottomOffset) {
      let height = null;
      height =
        window.innerHeight - ref.getBoundingClientRect().top - bottomOffset;
      return height;
    },

    resizeTable() {
      this.$nextTick(() => {
        this.tableHeight = this.returnTableHeight(this.$refs.tableDom, 100);
      }, 0);
    },
  },
};
</script>
 
<style lang="scss">
.el-select .el-input {
  width: 100% !important;
}

.header {
  text-align: center;
  line-height: 23px;
  font-size: 13px;
  border: 1px solid #ebeef5;
  padding: 10px 0;
  // font-weight: 510;
  // font-style: italic;
  // font-family: Haettenschweiler // , Helvetica, sans-serif Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif
}
</style>